package my.hnb.android.view.base;

import my.hnb.android.common.ActionEvent;
import my.hnb.android.common.AppInfo;
import my.hnb.android.common.ModelEvent;
import my.hnb.android.constant.EventConstant;
import my.hnb.android.constant.IntentConstants;
import my.hnb.android.listenner.OnEventListener;
import my.hnb.android.network.HTTPClient;
import my.hnb.android.ultils.MyLog;
import my.hnb.android.ultils.StringUtil;
import my.hnb.android.ultils.TraceUnexceptionLog;
import my.hnb.songnhac.R;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.code.microlog4android.appender.LogCatAppender;
import com.google.code.microlog4android.config.PropertyConfigurator;

public abstract class BaseActivity extends FragmentActivity implements DialogInterface.OnCancelListener,
		OnEventListener {

	// chuoi action cua cac broadcast message
	public static final String BROADCAST_ACTION = "my.hnb.android.songnhac";
	// kiem tra activity da finish hay chua
	public boolean isFinished = false;
	// dialog hien thi khi request
	private ProgressDialog progressDlg;
	// header
	public TextView tvHeader;
	public TextView tvHeaderLeft;
	// loading
	ProgressBar pbloading;
	// header view
	private View rlHeader;
	public ImageView ivMenu;

	// broadcast receiver, nhan broadcast
	BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			int action = intent.getExtras().getInt("hnb.action.songnhac");
			int hasCode = intent.getExtras().getInt("hnb.hashCode.songnhac");
			if (hasCode != BaseActivity.this.hashCode()) {
				receiveBroadcast(action, intent.getExtras());
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		PropertyConfigurator.getConfigurator(this).configure();
		if (MyLog.logger.getNumberOfAppenders() == 0) {
			MyLog.logger.addAppender(new LogCatAppender());
		}
		AppInfo.getInstance().setAppContext(getApplicationContext());
		AppInfo.getInstance().setActivityContext(this);
		if (savedInstanceState != null) {
			if (savedInstanceState.containsKey(IntentConstants.INTENT_GLOBAL_BUNDLE)) {
				getIntent().putExtras(savedInstanceState.getBundle(IntentConstants.INTENT_GLOBAL_BUNDLE));
			}
			if (StringUtil.isNullOrEmpty(HTTPClient.sessionID)
					&& savedInstanceState.containsKey(IntentConstants.INTENT_SESSION_ID)) {
				HTTPClient.sessionID = savedInstanceState.getString(IntentConstants.INTENT_SESSION_ID);
			}
		}

		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		try {
			IntentFilter filter = new IntentFilter(BaseActivity.BROADCAST_ACTION);
			registerReceiver(receiver, filter);
			Thread.setDefaultUncaughtExceptionHandler(new TraceUnexceptionLog(this));
		} catch (Exception e) {
		}
	}

	/**
	 * create voi tham so co nhan broadcast hay khong
	 * 
	 * @author: BangHN
	 * @version: 1.0
	 * @since: Dec 30, 2011
	 */
	protected void onCreate(Bundle savedInstanceState, boolean broadcast) {
		super.onCreate(savedInstanceState);
		PropertyConfigurator.getConfigurator(this).configure();
		if (MyLog.logger.getNumberOfAppenders() == 0) {
			MyLog.logger.addAppender(new LogCatAppender());
		}
		AppInfo.getInstance().setAppContext(getApplicationContext());
		AppInfo.getInstance().setActivityContext(this);
		if (savedInstanceState != null) {
			if (savedInstanceState.containsKey(IntentConstants.INTENT_GLOBAL_BUNDLE)) {
				getIntent().putExtras(savedInstanceState.getBundle(IntentConstants.INTENT_GLOBAL_BUNDLE));
			}
			if (savedInstanceState != null) {
				if (savedInstanceState.containsKey(IntentConstants.INTENT_GLOBAL_BUNDLE)) {
					getIntent().putExtras(savedInstanceState.getBundle(IntentConstants.INTENT_GLOBAL_BUNDLE));
				}
				if (StringUtil.isNullOrEmpty(HTTPClient.sessionID)
						&& savedInstanceState.containsKey(IntentConstants.INTENT_SESSION_ID)) {
					HTTPClient.sessionID = savedInstanceState.getString(IntentConstants.INTENT_SESSION_ID);
				}
			}
		}

		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		if (broadcast) {
			try {
				IntentFilter filter = new IntentFilter(BaseActivity.BROADCAST_ACTION);
				registerReceiver(receiver, filter);
				Thread.setDefaultUncaughtExceptionHandler(new TraceUnexceptionLog(this));
			} catch (Exception e) {
			}
		}

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		if (getIntent().getExtras() != null) {
			outState.putBundle(IntentConstants.INTENT_GLOBAL_BUNDLE, getIntent().getExtras());
		}
		if (!StringUtil.isNullOrEmpty(HTTPClient.sessionID)) {
			outState.putString(IntentConstants.INTENT_SESSION_ID, HTTPClient.sessionID);
		}
		super.onSaveInstanceState(outState);
	}

	@Override
	public void finish() {
		isFinished = true;
		super.finish();
	}

	@Override
	public void finishActivity(int requestCode) {
		isFinished = true;
		super.finishActivity(requestCode);
	}

	@Override
	public void setContentView(int layoutResID) {
		super.setContentView(R.layout.layout_base_main);
		LinearLayout mainContent = (LinearLayout) findViewById(R.id.llContent);
		LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		inflater.inflate(layoutResID, mainContent);

		initialize();
	}

	@Override
	public void setContentView(View view) {
		// TODO Auto-generated method stub
		super.setContentView(R.layout.layout_base_main);
		LinearLayout main = (LinearLayout) findViewById(R.id.llContent);
		main.addView(view);
		initialize();
	}

	private void initialize() {
		LinearLayout rootView = (LinearLayout) findViewById(R.id.llContent);
		LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		rlHeader = inflater.inflate(R.layout.layout_base_header, null);
		pbloading = (ProgressBar) rlHeader.findViewById(R.id.pbloading);
		ivMenu = (ImageView) rlHeader.findViewById(R.id.ivMenu);
		tvHeader = (TextView) rlHeader.findViewById(R.id.tvHeader);
		tvHeader.setVisibility(View.GONE);
		
		tvHeaderLeft = (TextView) rlHeader.findViewById(R.id.tvLeft);
		tvHeaderLeft.setVisibility(View.GONE);
		rootView.addView(rlHeader, 0);
	}

	protected void setTitleText(CharSequence title) {
		tvHeader.setText(title);
		tvHeader.setVisibility(View.VISIBLE);
	}
	
	protected void setTitleLeftText(CharSequence title) {
		tvHeaderLeft.setText(title);
		tvHeaderLeft.setVisibility(View.VISIBLE);
	}

	
	
	protected void setLoading(int visible) {
		pbloading.setVisibility(visible);
	}

	@Override
	protected void onDestroy() {
		try {
			unregisterReceiver(receiver);
		} catch (Exception e) {
		}
		System.gc();
		System.runFinalization();
		System.gc();
		super.onDestroy();
	}

	public void onCancel(DialogInterface dialog) {
	}

	/**
	 * show msg notify to user
	 * 
	 * @author: BangHN
	 * @version: 1.0
	 * @since: Oct 12, 2011
	 */
	public AlertDialog showMessage(String mes) {
		AlertDialog alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.setMessage(mes);
		alertDialog.setButton("Đồng ý", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				// xu ly vao controller o day.....
				dialog.dismiss();
				return;

			}
		});
		alertDialog.show();
		return alertDialog;
	}

	public void showProgressDialog(String content) {
		showProgressDialog(content, true);
	}

	public void showProgressDialog(String content, boolean cancleable) {
		progressDlg = ProgressDialog.show(this, "", content, true, true);
		// progressDlg.setIndeterminateDrawable(getResources().getDrawable(R.drawable.anim_loading));
		progressDlg.setCancelable(cancleable);
		progressDlg.setOnCancelListener(this);
	}

	public void closeProgressDialog() {
		if (progressDlg != null) {
			progressDlg.dismiss();
			progressDlg = null;
		}
	}

	public void showProgressPercentDialog(String content) {
		progressDlg = new ProgressDialog(this);
		progressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDlg.setMessage(content);
		progressDlg.setCancelable(false);
		progressDlg.show();
	}

	public void updateProgressPercentDialog(int percent) {
		if (progressDlg != null) {
			progressDlg.setProgress(percent);
		}
	}

	public void closeProgressPercentDialog() {
		if (progressDlg != null) {
			progressDlg.dismiss();
			progressDlg = null;
		}
	}

	/**
	 * send broadcast toi cac view
	 * 
	 * @author: BangHN
	 * @version: 1.0
	 * @since: Dec 30, 2011
	 */
	public void sendBroadcast(int action, Bundle bundle) {
		Intent intent = new Intent(BROADCAST_ACTION);
		bundle.putInt("hnb.action.songnhac", action);
		bundle.putInt("hnb.hashCode.songnhac", intent.getClass().hashCode());
		intent.putExtras(bundle);
		sendBroadcast(intent);
	}

	/**
	 * nhan msg khi co intent sent boi broadcast
	 * 
	 * @author: BangHN
	 * @version: 1.0
	 * @since: Dec 30, 2011
	 */
	public void receiveBroadcast(int action, Bundle bundle) {
		switch (action) {
		case EventConstant.ACTION_FINISH_APP:
			finish();
			break;
		default:
			break;
		}
	}

	/**
	 * Xu ly model tren tang view
	 * 
	 * @author: BangHN
	 * @version: 1.0
	 * @since: Jan 1, 2012
	 */
	public void handleModelViewEvent(ModelEvent modelEvent) {
		ActionEvent e = modelEvent.getActionEvent();
		switch (e.action) {
		}
	}

	/**
	 * Xu ly loi model tren tang view
	 * 
	 * @author: BangHN
	 * @version: 1.0
	 * @since: Jan 1, 2012
	 */
	public void handleErrorModelViewEvent(ModelEvent modelEvent) {

	}

	@Override
	public void onEvent(View v, int action, Object userData) {
		switch (action) {

		default:
			break;
		}
	}

}
